package com.controller;

import com.pojo.Supplier;
import com.pojo.SysUser;
import com.service.SupplierService;
import com.util.Page;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.math.RandomUtils;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/supplier")
public class SupplierController {

    private static final Logger logger=Logger.getLogger(SupplierController.class);
    @Resource
    private SupplierService supplierService;

    @RequestMapping("/list")
    public String getSupplierList(Model model, String querySupName,
                                  String querySupCode, @RequestParam(defaultValue = "1") int pageIndex){
        List<Supplier> supplierList=null;
        Page<Supplier> supplierPage = new Page<Supplier>();
        try {
            //设置总数据量
            supplierPage.setTotalPage(supplierService.count(querySupCode, querySupName));
            //设置总页数
            supplierPage.setTotalPageSize();
            //当前页
            supplierPage.setPageIndex(pageIndex);
            //获取当前页数据
            supplierPage.setList(supplierService.select(querySupCode, querySupName, supplierPage.getPageIndex(), supplierPage.getPageSize()));

            supplierList=supplierService.select(querySupCode,querySupName,supplierPage.getPageIndex(),supplierPage.getPageSize());

            model.addAttribute("supplierList",supplierList);

            model.addAttribute("querySupCode", querySupCode);
            model.addAttribute("querySupName", querySupName);

            model.addAttribute("supplierList", supplierPage.getList());
            model.addAttribute("totalPageCount", supplierPage.getTotalPageSize());
            model.addAttribute("totalCount", supplierPage.getTotalPage());
            model.addAttribute("currentPageNo", supplierPage.getPageIndex());

        }catch (Exception e){
            e.printStackTrace();
            logger.error("供货商列表接口访问失败!");
            return "redirect:/supplier/toSysError";
        }
        return "supplier/list";
    }
    @RequestMapping(value = "/toSysError")
    public String sysError(){
        return "sysError";
    }

    @RequestMapping("/toAdd")
    public String toAdd(){
        return "supplier/add";
    }

    @RequestMapping("/add")
    public String add(Supplier supplier, HttpSession session, HttpServletRequest request,
                      @RequestParam(value = "attachs",required = false) MultipartFile[] attachs){
        String companyLicPicPath=null;
        String orgCodePicPath=null;
        String errorInfo=null;
        boolean flag=true;
        String path=request.getSession().getServletContext().getRealPath("statics"+ File.separator+"uploadfiles");
        logger.info("文件路径:"+path);
        for (int i = 0; i <attachs.length ; i++) {
            MultipartFile attach=attachs[i];
            if(i==0){
                errorInfo="uploadFileError";
            }else if(i==1){
                errorInfo="uploadWpError";
            }
            String oldFileName=attach.getOriginalFilename();
            logger.info("原文件名:"+oldFileName);
            String prefix= FilenameUtils.getExtension(oldFileName);
            logger.info("原文件后缀:"+prefix);
            int filesize=500000;
            logger.debug("文件上传大小:"+attach.getSize());
            if(attach.getSize()>filesize){
                request.setAttribute(errorInfo,"*上传大小不得超过500KB");
                flag=false;
            }else if(prefix.equalsIgnoreCase("jpg")||
            prefix.equalsIgnoreCase("png")||prefix.equalsIgnoreCase("jpeg")||
            prefix.equalsIgnoreCase("pneg")){
                String fileName=System.currentTimeMillis()+ RandomUtils.nextInt(1000000)+"_Personal."+prefix;
                logger.debug("新文件名:"+fileName);
                File targetFile=new File(path);
                if(!targetFile.exists()){
                    targetFile.mkdirs();
                }
                try {
                    attach.transferTo(new File(targetFile,fileName));
                } catch (IOException e) {
                    e.printStackTrace();
                    request.setAttribute(errorInfo,"*文件上传失败");
                    flag=false;
                }
                if(i==0){
                    companyLicPicPath=File.separator+"statics"+File.separator+"uploadfiles"+File.separator+fileName;
                }else if(i==1){
                    orgCodePicPath=File.separator+"statics"+File.separator+"uploadfiles"+File.separator+fileName;
                }
                logger.debug("companyLicPicPath:"+companyLicPicPath);
                logger.debug("orgCodePicPath:"+orgCodePicPath);
            }else{
                request.setAttribute(errorInfo,"*文件上传图片格式不正确");
                flag=false;
            }
        }
        if(flag){
            supplier.setCreatedUserId(((SysUser) session.getAttribute("USER_SESSION")).getId());
            supplier.setCompanyLicPicPath(companyLicPicPath);
            supplier.setOrgCodePicPath(orgCodePicPath);
            if(supplierService.add(supplier)){
                return "redirect:/supplier/list";
            }
        }
        return "supplier/add";
    }
    @RequestMapping("/view/{id}")
    public String view(@PathVariable String id,Model model){
        Supplier supplier=supplierService.getSupplierById(id);
        model.addAttribute(supplier);
        return "supplier/view";
    }

    @RequestMapping("/toUpdate")
    public String toUpdate(@RequestParam String uid,Model model){
        logger.debug("跳转到修改用户信息页面");
        Supplier supplier=supplierService.getSupplierById(uid);
        model.addAttribute(supplier);
        return "supplier/update";
    }
    @RequestMapping("/update")
    public String update(Supplier supplier,HttpSession session){
        logger.debug("修改用户信息");
        supplier.setUpdatedUserId(((SysUser) session.getAttribute("USER_SESSION")).getId());
        if(supplierService.update(supplier)){
            return "redirect:/supplier/list";
        }
        return "supplier/update";
    }

}

